<template>
    <nly-content-wrapper class="content-warpper-2">
        <div class="content-header-2">
            <!--按钮-->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <!-- <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="!isCollected">
                            <div class="btns" @click="tabMyCollect">
                                <a-icon class="btns-icon" type="heart" />
                                <div class="btns-text">我的关注</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="isCollected">
                            <div class="btns" @click="tabMyCollect">
                                <a-icon class="btns-icon" style="color:red" type="heart" />
                                <div class="btns-text">退出关注</div>
                            </div>
                        </a-col> -->
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:add')">
                            <div class="btns" @click="AddItem">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:edit')">
                            <div class="btns" @click="EdiItem">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">编辑</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:disable')">
                            <div style="position:relative">
                                <div class="btns" @click="disable">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                                <div style="position:absolute;width:2px;height:36px;border-radius:6px;background:#ccc;top:0px;right:0px;"></div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:export')">
                            <div class="btns" @click="() => (exportVisible = true)">
                                <a-icon class="btns-icon" type="export" />
                                <div class="btns-text">导出</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:share')">
                            <div class="btns" @click="openShareBox()">
                                <a-icon class="btns-icon" type="user" />
                                <div class="btns-text">共享</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="!isCollected">
                            <div class="btns" @click="collectAdd()">
                                <a-icon class="btns-icon" type="heart" />
                                <div class="btns-text">关注客户</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="collectOut()">
                                <a-icon class="btns-icon" type="frown" />
                                <div class="btns-text">取消关注</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:goBack')">
                            <div class="btns" @click="potentialSave">
                                <a-icon class="btns-icon" type="rollback" />
                                <div class="btns-text">退回</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('crm:deals:distribution')">
                            <div class="btns" @click="distribution()">
                                <a-icon class="btns-icon" type="branches" />
                                <div class="btns-text">分配</div>
                            </div>
                        </a-col>
                        <!-- <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="onShowSerch">
                                <a-icon class="btns-icon" type="file-search" />
                                <div class="btns-text">查询</div>
                            </div>
                        </a-col> -->
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="showMySet">
                                <a-icon class="btns-icon" type="setting" />
                                <div class="btns-text">自定义列</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="GetCustomizeList">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">同步设置</div>
                            </div>
                        </a-col>
                    </a-col>
                    
                </a-row>
            </div>
            <!-- 查询方案 -->
            <a-col :span="24">
                <div class="search-btn-box-gw">
                    <div class="item-small" ref="planLi">
                        <ul>
                            <li class="item-plan" :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                            <li class="item-plan" :title="item.searchName" :class="item.id == planActive?'active':''" v-for="(item,index) in userSearchList" :key="index" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            <li class="item-plan" @click="onShowSerch">
                                <!-- <a-icon class="icon-searh-btn" type="file-search" /> 查询 -->
                                自定查询
                                <a-icon class="icon-searh-btn" type="search" />
                            </li>
                        </ul>
                    </div>
                    <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                        <a-icon v-if="iconDirection" type="down" />
                        <a-icon v-else type="up" />
                    </div>
                </div>
            </a-col>
            <!-- 查询方案结束 -->
            <!-- <nly-row class="col-12">
                <nly-row class="col-12">
                    <fixed-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></fixed-condition>
                    <div class="mb-1">
                        <nly-button @click="showFunction" variant="info" button-class="mr-2"><i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />{{ show ? "折 叠" : "展 开" }}
                        </nly-button>
                        <nly-button variant="info" @click="onSerch" button-class="mr-2" :disabled="loading">查询</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="reset" :disabled="loading">重置</nly-button>

                        <nly-button variant="info" @click="showUsModal" button-class="mr-2">保存常用查询</nly-button>

                    </div>
                </nly-row>
            </nly-row>
            <dynamic-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition> -->

            <a-drawer class="mySet" title="自定义列" width="520" height="300" @close="onMySetClose" :visible="mySetVisible">
                <a-checkbox-group v-model="mySetcheckedListLocal" :options="mySetplainOptions" @change="onMySetChange" />
                <nly-col xs="12" sm="12" class="form-inline align-self-start mt-3" style>
                    <nly-button-group>
                        <nly-button variant="danger" @click="onMySetClose" button-class="mr-2">关闭</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="saveMyShow">确定</nly-button>
                    </nly-button-group>
                </nly-col>
            </a-drawer>
            <nly-container fluid></nly-container>
        </div>
        <!-- 功能操作 -->
        <!-- <div>
            <a-button type="primary" class="crm-btn" @click="tabMyCollect" v-show="!isCollected"><i class="fas fa-flag fa-flag-more"></i>我的关注</a-button>
            <a-button type="" class="crm-btn" @click="tabMyCollect" v-show="isCollected"><i class="fas fa-flag fa-flag-more"></i>退出关注</a-button>
            <a-button type="primary" class="crm-btn" @click="collectAdd" v-show="!isCollected">关注客户</a-button>
            <a-button type="primary" class="crm-btn" @click="collectOut">取消关注</a-button>
            <a-button type="primary" class="crm-btn" @click="potentialSave" v-if="permissions.includes('crm:deals:goBack')">退回</a-button>
            <a-button type="primary" class="crm-btn" @click="distribution" v-if="permissions.includes('crm:deals:distribution')">分配</a-button>
            <a-button type="primary" class="crm-btn" @click="EdiItem" v-if="permissions.includes('crm:deals:edit')">编辑</a-button>
            <a-button type="primary" class="crm-btn" @click="AddItem" v-if="permissions.includes('crm:deals:add')">新增</a-button>
            <a-dropdown type="primary">
                <a-menu slot="overlay">
                    <a-menu-item key="2" @click="disable" v-if="permissions.includes('crm:deals:disable')">
                        <a-icon type="user" />删除
                    </a-menu-item>
                    <a-menu-item key="4" @click="() => (shareVisible = true)">
                        <a-icon type="user" />共享
                    </a-menu-item>
                    <a-menu-item key="5" @click="() => (exportVisible = true)" v-if="permissions.includes('crm:deals:export')">
                        <a-icon type="user" />导出
                    </a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px">
                    更多
                    <a-icon type="down" />
                </a-button>
            </a-dropdown>
            <i class="fa fa-fw fa-cog fieldSet " @click="showMySet"></i>
        </div> -->

        <nly-content>
            <!-- 列表 -->
            <a-table id="deals_tb" :columns="columns" :rowClassName="rowClassName" :data-source="data" :scroll="{ x: 500, y: 500 }" bordered :loading="loading" :pagination="pagination" @change="onTableChange" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}">
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record,'touch')">
                    <i :class="record.collectId > 0 ? 'fas fa-heart fa-heart-red':'fas fa-flag fa-flag-white'"></i>
                    {{text}}
                </a>
                <a slot="crmNo" slot-scope="text, record" @click="goToDetail(record,'touch')">
                    {{text}}
                </a>
                <div slot="shareType" slot-scope="text,record" v-if="text">
                    <span v-if="userInfo.id == record.collarUserId">已共享给‘{{record.shareUserName}}’</span>
                    <span v-else>由‘{{record.collarUserName}}’共享</span>
                </div>
                <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                    <a-input v-model="crmNameValue" :placeholder="`搜索${column.title}`" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                    <a-button size="small" style="width: 90px; margin-right: 8px" @click="() => handleReset(clearFilters)">
                        重置
                    </a-button>
                    <a-button type="primary" icon="search" size="small" style="width: 90px;" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                        搜索
                    </a-button>
                </div>
                <a-icon slot="filterIcon" type="filter" theme="filled" :style="{ color: '#444',marginRight:'5px' }" />
            </a-table>
            <!-- modal 弹窗  -->
            <drag-modal :title="editItem.id ? '编辑成交客户' : '新增成交客户'" :visible="ModalVisible" @ok="onSubmit" @cancel="hideModal" class="add-or-edit-modal">
                <!-- 动态 表单  -->
                <div class="min-box">
                    <dynamic-form :formPostData="formPostData" :initFormData="initFormData" :errors="formErrors" :isOk="isFromShow" :blurEventMap="blurEventMap"></dynamic-form>
                </div>
                <template slot="footer">
                    <div>
                        <a-button type="primary" @click="onSubmit">确认</a-button>
                        <a-button @click="hideModal" class="margin-left-10">关闭</a-button>
                    </div>
                </template>
            </drag-modal>
            <!-- 常用查询名称编辑框 -->
            <a-modal title="保存常用查询" :visible="UsVisible" @ok="UserSearchSave" @cancel="hideUsModal">
                <nly-row class="form-inline" v-show="isOk">
                    <form-input title="名称" rightStyle="flex-grow:1;" class="ml-1 mb-1" style="flex:0.8;" :error="myUsErrors['userSearchEditItem.searchName']" :required="true" v-model="userSearchEditItem.searchName"></form-input>
                </nly-row>
            </a-modal>

            <a-modal v-model="userModal" lg hide-footer title="分配客户给" width="300px">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-input-search style="margin-bottom: 8px" placeholder="输入用户名称" @change="onChange" />
                    <div v-show="treeAShow">
                        <a-tree :selected-keys="selectedUserKeys" :tree-data="userSearchData" :expanded-keys="expandedUserKeys" @expand="expanedChange" :defaultExpandAll="true" @select="onUserSelect" :checkable="false" :show-icon="true">
                            <a-icon slot="user" type="user" />
                        </a-tree>
                    </div>
                    <div v-show="treeBShow">
                        <a-tree :selected-keys="selectedUserKeys" :tree-data="userAllData" :defaultExpandAll="true" :checkable="false" @select="onUserSelect" :show-icon="true">
                            <a-icon slot="user" type="user" />
                        </a-tree>
                    </div>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="distributionSave">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="() => {this.userModal=false}">关闭</a-button>
                </template>
            </a-modal>

            <a-modal v-model="shareUserVisible" title="用户选择" centered on-ok="handleok" width="300px">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-input-search style="margin-bottom: 8px" placeholder="输入用户名称" @change="onChange" />
                    <div v-show="treeAShow">
                        <a-tree v-model="checkedUserKeys" :tree-data="userSearchData" :show-icon="true" :expanded-keys="expandedUserKeys" @expand="expanedChange" :defaultExpandAll="true" checkable @check="shareUserCheck">
                            <a-icon slot="user" type="user" />
                        </a-tree>
                    </div>
                    <div v-show="treeBShow">
                        <a-tree v-model="checkedUserKeys" :tree-data="userAllData" :show-icon="true" checkable :defaultExpandAll="true" @check="shareUserCheck">
                            <a-icon slot="user" type="user" />
                        </a-tree>
                    </div>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="() => (shareUserVisible = false)">确定</a-button>
                    <a-button key="back" @click="() => (shareUserVisible = false)">关闭</a-button>
                </template>
            </a-modal>

            <a-modal v-model="exportVisible" title="导出客户数据文件" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                    <a-radio-group v-model="exportRadioValue">
                        <p>
                            <a-radio value="1">导出所选客户：{{exportValue || 0}}条</a-radio>
                        </p>
                        <p>
                            <a-radio value="2">导出符合条件客户：{{pagination.total || 0}}条</a-radio>
                        </p>
                    </a-radio-group>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" icon="download" @click="exportCrmData">导出</a-button>
                    <a-button key="back" @click="() => (exportVisible = false)" icon="close">取消</a-button>
                </template>
            </a-modal>

            <a-modal v-model="shareVisible" title="客户共享" centered on-ok="handleok" width="650px">
                <div style="margin-left:30px;height: 250px;">
                    <div>
                        * 有效时间至：
                        <a-date-picker v-model="shareTime" show-time format="YYYY-MM-DD" style="width: 320px;" placeholder="有效时间" />
                        <a-checkbox style="margin-left: 30px;" @change="shareCheckChange" :checked="shareEndCheck">永久有效</a-checkbox>
                    </div>
                    <div style="margin-top: 20px;margin-left: 5px;">
                        相关模块：
                        <a-checkbox-group v-model="checkedModelList" :options="modelOptions" />
                    </div>
                    <div style="margin-top: 30px;margin-left: 5px;">
                        共享用户：
                        <a-input-search read-only v-model="shareUserNames" style="width: 420px" placeholder="选择用户" @change="() => (shareUserVisible = true)" @click="() => (shareUserVisible = true)" @search="() => (shareUserVisible = true)" />
                    </div>
                </div>
                <template slot="footer">
                    <a-button key="submit" type="primary" @click="saveShare">保存</a-button>
                    <a-button key="back" @click="() => (exportVisible = false)">取消</a-button>
                </template>
            </a-modal>

            <!-- <a-modal v-model="mergeVisible" title="客户合并" centered on-ok="handleok" width="650px">
                    <div style="overflow-y:scroll;">
                    <a-table
                        :columns="mergeColumns"
                        :data-source="mergeData"
                        bordered
                        :pagination="false"
                        :row-selection="{selectedRowKeys: selectedMergeKeys, onChange: mergeSelection, type: 'radio'}"
                    />
                    </div>
                    <template slot="footer">
                    <a-button key="submit" type="primary" @click="saveMergeCrm">保存</a-button>
                    <a-button key="back" @click="() => (mergeVisible = false)">取消</a-button>
                    </template>
                </a-modal> -->

            <!-- 查询方案弹窗 -->
            <a-modal class="search-wrapper-box-crm" :visible="visibleSearchPlan" title="查询" @cancel="cancel" width="1000px">
                <div class="content-box">
                    <div class="left-box">
                        <a-row class="btn-wrapper">
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?UserSearchSave():''">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">保存</div>
                                </div>
                            </a-col>
                            <a-col :span="6">
                                <div class="btns" @click="showUsModal(2)">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">另存</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?showUsModal(1):''">
                                    <a-icon class="btns-icon" type="edit" />
                                    <div class="btns-text">修改</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?onUserSearchDelete({key:planActive}):''">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                            </a-col>
                        </a-row>
                        <div class="plan-list">
                            <ul>
                                <li :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                                <li v-for="(item,index) in userSearchList" :key="index" :class="item.id == planActive?'active':''" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            </ul>
                        </div>
                    </div>
                    <div class="right-box">
                        <a-tabs default-activeKey="1" @change="callback">
                            <a-tab-pane key="1" tab="查询条件">
                                <dynamic-condition v-if="visibleSearchPlan" :checkable="true" :conditions="conditions" :show="true" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition>
                            </a-tab-pane>
                        </a-tabs>
                    </div>
                </div>
                <template slot="footer">
                    <div>
                        <!-- <div style="float:left">
                            <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                                下次以此方案进入
                            </a-checkbox>
                        </div> -->
                        <a-button type="primary" @click="onSerch">查询</a-button>
                        <a-button @click="cancel" class="margin-left-10">取消</a-button>
                    </div>
                </template>
                <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
                    <a-input v-model="saveAsName" placeholder="请输入查询方案名称"></a-input>
                    <template slot="footer">
                        <div>
                            <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                            <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                        </div>
                    </template>
                </a-modal>
            </a-modal>
            <drawerCrm :drawerVisible.sync="drawerVisible" :routeUrl="routeUrl" :title="drawerTitle" :dataItem="dataItem" @collectOut="collectOut" @collectAdd="collectAdd" @dealSave="dealSave" @openShareBox="openShareBox" @release="release" @distribution="distribution" @receive="receive"></drawerCrm>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { mapState } from "vuex";
import { listToMap } from "@/utils/tool/map";
import { deepCopy } from "@/utils/tool/object";
import { Controlwidth } from "@/utils/antTableComponents";
import getDate from "@/utils/tool/date";
import {
    PageList,
    Save as SaveCustomer,
    dealSave,
    potentialSave,
    saveShare,
    distributionSave,
    disable,
    collectAdd,
    collectOut,
    combineSave,
    exportData,
} from "@/api/crm/customer";
import { clearValue, clearKeys } from "@/utils/tool/object";
import { officeUserListToTree, searchInTreeData } from "@/utils/tree";
import { initValidator, checkAll } from "@/utils/validator/validator";
import { TreeDataOffice } from "@/api/office";
import { getPhonetic } from "@/api/common/py";
import moment from "moment";

import dynamicList from "@/mixins/dynamicList";

import MiddleUtils from '@/utils/middle-utils'
import drawerCrm from "@/components/Crm/drawer";

export default {
    mixins: [dynamicList],
    data () {
        const modelOptions = [
            {
                label: "联系人",
                value: "linkMan"
            },
            {
                label: "联系记录",
                value: "touch"
            },
            {
                label: "客户文档",
                value: "files"
            },
            {
                label: "需求",
                value: "requirement"
            },
            {
                label: "收货人信息",
                value: "consignee"
            },
            {
                label: "报价单",
                value: "price"
            },
            // {
            //   label: "合同",
            //   value: 7
            // },
            // {
            //   label: "跟进计划",
            //   value: 8
            // },
            {
                label: "商机",
                value: "business"
            },
            // {
            //   label: "主管评价",
            //   value: 11
            // }
        ];

        const checkedModelList = [];

        const mergeColumns = [
            {
                title: "客户名称",
                dataIndex: "crmName",
                align: "left"
            },
            {
                title: "所属人",
                dataIndex: "collarUserName",
                align: "left"
            }
        ];

        //表格 头部 可伸缩
        return {
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------

            //gw 2021年8月16日11:04:08
            visibleSearchPlan: false,
            //gw 2021年8月16日11:04:16
            searchType: 2, //0:线索客户 1.潜在客户 2.成交客户  3.联系人 4.联系人记录   
            source: "crm",
            crmType: 2, //0:线索客户 1.潜在客户 2.成交客户  3.联系人 4.联系人记录    
            isCheck:true,       //是否校验
            customRenderCode: ["crmName", "shareType", "crmNo"], //table 使用插槽的列
            FixedConditionKeys: ["crmName", "phonetic"],  //固定的搜索条件的Key
            selectedUserKeys: [], //用户选择key
            selectedUserName: "", //用户tree选择name
            selectedMergeKeys: [], //客户合并key
            userAllData: [], //所有用户tree数据
            expandedUserKeys: [], //用户tree展开keys
            userSearchData: [], //用户tree搜索数据
            treeAShow: false, //搜索用户tree
            treeBShow: true, //用户tree
            exportVisible: false, //导出弹窗
            exportValue: 0, //要导出选中的数量
            exportRadioValue: "1", //导出redio值
            shareVisible: false, //共享弹窗
            shareEndCheck: false, //共享时间是否永久
            checkedModelList: checkedModelList, //共享模块选中数据
            modelOptions, //共享模块数据
            shareUserVisible: false, //共享用户弹窗
            checkedUserKeys: [], //共享用户keys
            shareUserNames: "", //共享用户名
            shareUserId: "", //共享用户id
            shareTime: null, //共享时间
            mergeVisible: false, //合并弹窗
            mergeColumns, //合并table字段
            mergeData: [], //合并table数据
            crmCheckedDatas: [], //客户选中的数据
            userModal: false, //分配弹窗

            drawerVisible: false,//客户详情抽屉
            routeUrl: '',
            drawerTitle: '',
            dataItem: {},
            crmNameValue: null,
            rowClassName: (record, index) => {
                if (record.clickActive) {
                    return 'click-table-active'
                }
            },
        };
    },
    components: {
        drawerCrm,//客户系统抽屉显示详情
    },
    watch: {
        $route: {
            handler (nv, ov) {
                //离开路由关闭 右侧详情抽屉
                this.drawerVisible = false;
            },
            deep: true
        },
    },
    activated () {
        //通过消息跳转过来需要弹出 侧边详细客户信息
        let id = this.$route.query.id;
        if (id) {
            detail({ id }).then(response => {
                if (response.code === 200) {
                    this.goToDetail(response.data, 'crm')
                }
            }).catch(error => { });
        }
    },
    mounted () {
        TreeDataOffice({ isLoadUser: 2 }).then(response => {
            const { data } = response;
            const childrenNav = [];
            officeUserListToTree(data, childrenNav, "0");
            this.userAllData = childrenNav;
            this.userSearchData = childrenNav;
        });
        MiddleUtils.$on('syncList', (value) => {
            if(this.$route.path == '/crm/customer/deals'){
                console.log("刷新syncList---服务中客户");
                this.PageList();
            }
        })
    },
    updated () {
        Controlwidth("deals_tb", 50);
    },
    computed: {

    },
    methods: {
        //跳转到 客户详情
        goToDetail (item, tabkey) {
            const { permissions } = this;
            if (!this.customerId && permissions.includes("crm:deals:edit")) {
                // this.$router.push(`/crm/customer/detail/${item.crmName}/${item.id}/${tabkey}`)
                this.drawerVisible = true;
                this.routeUrl = window.location.host + `/crm/customer/detail/${item.crmName}/${item.id}/${tabkey}`;
                this.drawerTitle = item.crmName;
                this.dataItem = item;
                this.$forceUpdate();
                //给点击的行一个颜色
                this.data.map(d => {
                    this.$set(d, 'clickActive', false)
                });
                this.$set(item, 'clickActive', true)
            }
        },
        //添加
        AddItem () {
            const { formPostData, formErrors } = this;
            clearKeys(formErrors);
            this.isFromShow = true;
            this.ModalVisible = true;
            console.log("AddItem_formErrors->", formErrors)
        },
        //编辑
        EdiItem () {
            if (this.selectedKeys.length != 1) {
                this.$message.warn("请选择一条客户数据");
                return false;
            }
            const item = this.crmCheckedDatas.find(f => f.id == this.selectedKeys[0]);
            this.goToDetail(item, 'crm');
        },
        onSerch () {
            const { postData } = this;
            postData.page.current = 1;
            this.PageList();
            this.cancel();
        },
        // 获取列表
        PageList (backId) {
            this.selectedKeys = [];
            const { postData, onOffDefineFields } = this;
            console.log("潜在客户——搜索条件：", onOffDefineFields);
            postData.dtos = onOffDefineFields;
            postData.page.size = this.pagination.pageSize;
            this.loading = true;
            PageList(postData).then(response => {
                this.loading = false;
                console.log("获取潜在客户列表", response);
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    //转换自定义数据数据
                    this.defineFieldsAddToData(records);

                    this.data = records;
                    console.log("转换后的数据：records", records);
                    Object.assign(this.pagination, {
                        total
                    });
                    //客户保存成功过后直接跳入详情页面
                    if (backId) {
                        const item = this.data.find(f => f.id == backId);
                        this.goToDetail(item, 'crm');
                    }
                } else {
                    this.data = [];
                    this.$message.error(response.message);
                }
            }).catch(error => {
                this.loading = false;
            });
        },
        //提交表单
        onSubmit () {
            const {
                isCheck,
                crmType,
                formRules,
                formPostData,
                formErrors,
                onOffDefineFields
            } = this;
            //全部校验一次
            checkAll(this, formRules, formPostData, formErrors);
            if (Object.keys(formErrors).length > 0) {
                this.isFromShow = false;
                this.$nextTick(function () {
                    this.isFromShow = true;
                });
                return false;
            }
            //自定义字段 重组
            let defineFieldsSets = onOffDefineFields.filter(f => f.dataType == 2);
            let defineFields = {};
            //获取重组后的自定义集合
            this.getDefineFields(defineFields, formPostData, defineFieldsSets);
            Object.assign(formPostData, {
                isCheck,
                crmType,
                defineFields: JSON.stringify(defineFields)
            });
            formPostData.isCustomer = 1;
            SaveCustomer(formPostData).then(response => {
                if (response.code === 200) {
                    this.$message.success("保存成功");
                    this.hideModal();
                    //刷新 列表
                    this.PageList(response.data);
                }
            })
        },
        //客户tabale check触发
        selection (keys, info) {
            this.selectedKeys = keys;
            console.log("rowKeys", info);
            this.crmCheckedDatas = info;
            this.exportValue = info.length;
        },
        //客户合并tabale check触发
        mergeSelection (keys, info) {
            this.selectedMergeKeys = keys;
            console.log(keys, info);
        },
        checkCrmKey () {
            if (this.selectedKeys.length < 1) {
                this.$message.warn("没有选择客户");
                return false;
            }
            return true;
        },
        //我的关注 切换
        tabMyCollect () {
            this.isCollected = !this.isCollected;
            Object.assign(this.postData, {
                isCollected: this.isCollected
            });
            this.PageList();
        },
        //关注客户
        collectAdd (id) {
            if (id) {
                collectAdd([id]).then(response => {
                    if (response.code == 200) {
                        this.$message.success("关注成功");
                        this.PageList();
                    } else {
                        this.$message.error(response.message);
                    }
                });
            } else {
                if (this.checkCrmKey()) {
                    console.log("关注.....");
                    collectAdd(this.selectedKeys).then(response => {
                        if (response.code == 200) {
                            this.$message.success("关注成功");
                            this.PageList();
                        }
                    });
                }
            }
        },
        //取消关注
        collectOut (id) {
            if (id) {
                collectOut([id]).then(response => {
                    if (response.code == 200) {
                        this.$message.success("取消关注成功");
                        this.PageList();
                    }
                });
            } else {
                if (this.checkCrmKey()) {
                    collectOut(this.selectedKeys).then(response => {
                        if (response.code == 200) {
                            this.$message.success("取消关注成功");
                            this.PageList();
                        }
                    });
                }
            }
        },
        //退回客户
        potentialSave () {
            if (this.checkCrmKey()) {
                let _this = this;
                this.$confirm({
                    title: '提示',
                    content: "确定要退回吗？",
                    okText: "确定",
                    cancelText: "取消",
                    onOk () {
                        potentialSave(_this.selectedKeys).then(response => {
                            if (response.code == 200) {
                                _this.$message.success("退回成功");
                                _this.PageList()
                            } else {
                                _this.$message.error(response.message);
                            }
                        });
                    },
                    onCancel () {
                    },
                });
            }
        },
        //分配弹窗
        distribution (id) {
            if (id) {
                this.selectedKeys = [id];
            }
            if (this.checkCrmKey()) {
                this.userModal = true;
                this.treeAShow = false;
                this.treeBShow = true;
            }
        },
        //分配客户
        distributionSave () {
            if (this.checkCrmKey()) {
                if (this.selectedUserKeys[0].indexOf("user") != -1) {
                    distributionSave({
                        type: 2,
                        collarUserId: this.selectedUserKeys[0].split("_")[0],
                        collarUserName: this.selectedUserName,
                        ids: this.selectedKeys.toString()
                    }).then(response => {
                        if (response.code == 200) {
                            this.$message.success("分配成功")
                            this.PageList();
                            this.userModal = false;
                        }
                    });
                } else {
                    this.$message.warn("请选择用户")
                }
            }
        },
        // shareEndCheck: false, //共享时间是否永久
        // checkedModelList: checkedModelList, //共享模块选中数据
        // modelOptions, //共享模块数据
        // shareUserVisible: false, //共享用户弹窗
        // checkedUserKeys: [], //共享用户keys
        // shareUserNames: "", //共享用户名
        // shareUserId: "", //共享用户id
        // shareTime: null, //共享时间
        //打开 共享 弹窗
        openShareBox (id) {
            if (id) {
                this.selectedKeys = [id];
            }
            if (!this.checkCrmKey()) return false;
            this.shareVisible = true;
            this.checkedModelList = [];
            this.shareEndCheck = false;
            this.checkedUserKeys = [];
            this.shareUserNames = '';
            this.shareUserId = '';
            this.shareTime = null;
        },
        //共享客户
        saveShare () {
            if (this.checkCrmKey()) {
                const formData = new FormData();
                formData.append("shareMenu", this.checkedModelList.toString());
                formData.append("shareUserId", this.shareUserId);
                formData.append("shareUserName", this.shareUserNames);
                if (this.shareTime) {
                    formData.append("shareTime", moment(this.shareTime).format("YYYY-MM-DD"));
                }
                formData.append("shareEnd", this.shareEndCheck ? 1 : 0);
                formData.append("shareType", 1);
                formData.append("ids", this.selectedKeys);
                saveShare(formData).then(response => {
                    if (response.code == 200) {
                        this.shareVisible = false;
                        this.$message.success("共享成功");
                        this.PageList();
                    }
                });
            }
        },
        shareCheckChange () {
            this.shareEndCheck = !this.shareEndCheck;
        },
        saveShareUser () {
            //保存要共享的人
            console.log(this.checkedUserKeys);
        },
        shareUserCheck (keys, info) {
            //共享人tree check事件
            this.shareUserNames = "";
            this.shareUserId = "";
            if (info.checkedNodes.length > 0) {
                for (let i = 0; i < info.checkedNodes.length; i++) {
                    const id = info.checkedNodes[i].data.props.id;
                    const name = info.checkedNodes[i].data.props.name;
                    if (id.indexOf("user") != -1) {
                        this.shareUserNames += name + ",";
                        this.shareUserId += id.split("_")[0] + ",";
                    }
                }
                this.shareUserNames = this.shareUserNames.slice(0, this.shareUserNames.length - 1);
                this.shareUserId = this.shareUserId.slice(0, this.shareUserId.length - 1);
            }
        },
        //删除
        disable () {
            if (this.checkCrmKey()) {
                let _this = this;
                this.$confirm({
                    title: "提示",
                    content: '您确定要删除吗？',
                    onOk () {
                        disable({ ids: _this.selectedKeys.toString(), status: 2 }).then(
                            response => {
                                if (response.code == 200) {
                                    _this.$message.success("删除成功");
                                    _this.PageList();
                                } else {
                                    _this.$message.success(response.message);
                                }
                            }
                        );
                    },
                    cancelText: '取消',
                    onCancel () {
                    },
                });
            }
        },
        //导出客户数据
        exportCrmData () {
            const { postData, onOffDefineFields } = this;
            console.log("客户系统——搜索条件：", onOffDefineFields);
            postData.dtos = onOffDefineFields;
            if (this.exportRadioValue == 1) {
                if (this.exportValue == 0) {
                    this.$message.warn("请选择要导出的客户");
                    return false;
                }
                postData.crmIds = this.selectedKeys;
            } else {
                if (this.pagination.total == 0) {
                    this.$message.warn("没有客户数据,不能导出");
                    return false;
                }
                postData.crmIds = null;
            }
            exportData(postData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "客户资料.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
                this.exportVisible = false;
                this.selectedKeys = [];
            });
        },
        //合并客户
        mergeCrm () {
            if (this.selectedKeys.length < 2) {
                this.$message.warn("至少选择2个客户");
                return false;
            }
            this.mergeData = this.crmCheckedDatas;
            this.mergeVisible = true;
        },
        //保存合并客户
        saveMergeCrm () {
            combineSave({
                ids: this.selectedKeys.toString(),
                id: this.selectedMergeKeys.toString()
            }).then(response => {
                if (response.code == 200) {
                    this.mergeVisible = false;
                    this.$message.warn("合并成功");
                    this.PageList();
                    this.mergeVisible = false;
                }
            });
        },
        //用户tree展开
        expanedChange (key, info) {
            this.expandedUserKeys = key;
        },
        //用户tree选择
        onUserSelect (key, info) {
            this.selectedUserKeys = key;
            this.selectedUserName = info.node.title;
            console.log(key, info);
        },
        //用户搜索
        onChange (e) {
            const value = e.target.value;
            console.log(value);
            if (value) {
                this.treeAShow = true;
                this.treeBShow = false;
                const keys = [];
                const treeData = searchInTreeData(keys, this.userAllData, "title", value);
                this.userSearchData = treeData;
                this.expandedUserKeys = keys;
            } else {
                this.treeAShow = false;
                this.treeBShow = true;
                //this.areaTreeData = treeAreaData;
                this.expandedUserKeys = [];
            }
        },//gw 2021年8月16日11:51:51
        cancel () {
            //置空临时查询条件
            // if (this.planActive == 0) {
            //     setTimeout(() => {
            //         this.onOffDefineFields.forEach(item => {
            //             item.value = '';
            //         });
            //     }, 200)
            // }
            this.visibleSearchPlan = false;
        },
        onShowSerch () {
            this.visibleSearchPlan = true;
        },
        //客户名称搜索
        handleReset (clearFilters) {
            //重置
            clearFilters();
            this.crmNameValue = '';
            this.onOffDefineFields.forEach(res => {
                if (res.code == 'crmName') {
                    res.value = this.crmNameValue;
                }
            })
            this.PageList()
        },
        handleSearch (key, confirm, col) {
            //table搜索
            confirm();
            console.log(key)
            console.log(confirm)
            console.log(col)
            if (col == 'crmName') {
                this.crmNameValue = key[0];
            }

            this.onOffDefineFields.forEach(res => {
                if (res.code == 'crmName') {
                    res.value = this.crmNameValue;
                }
            })
            this.PageList()
        },
    }
};
</script>
<style lang="less">
    @import '~@/style/crm.less';
</style>
